package com.yima.baseproj.module.sys.kindergarten;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yima.baseproj.module.sys.user.SysUserEntity;
import com.yima.baseproj.module.sys.user.SysUserService;

import com.yima.baseproj.utils.random_num.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Map;

@Service
public class KindergartenService extends ServiceImpl<KindergartenMapper,KindergartenEntity> {

    @Autowired
    private SysUserService userService;

    /**
     * 分页+模糊查询
     * @param page
     * @param searchModel
     * @return
     */
    public Page<Map> findAllByPage(Page page, KindergartenEntity searchModel) {

        //获取user 对应的kgId
        int kgId = userService.findKgIdByUserId();
        if(kgId==0){
            return baseMapper.findBySearchVo(page,searchModel);
        }else {
            return baseMapper.findByKgId(kgId,page);
        }
    }

    /**
     * 新增操作
     * @param kg
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(KindergartenEntity kg) {
        String kgCode = RandomUtil.getKgCode();
        kg.setKgCode(kgCode);
        baseMapper.insert(kg);
        System.out.println(kgCode);
    }

    /**
     * 根据id查询幼儿园信息
     * @param id
     * @return
     */
    public KindergartenEntity findById(int id){
        return  baseMapper.selectById(id);
    }

    /**
     * 修改幼儿园信息
     * @param kg
     */
    @Transactional(rollbackFor = Exception.class)
    public void edit(KindergartenEntity kg){
         baseMapper.updateById(kg);
    }

    /**
     * 根据id
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delByIds(int id) {
            baseMapper.deleteById(id);
    }

    /**
     * 得到幼儿园列表
     * @param kg
     */
    public List<Map> findAllByList(KindergartenEntity kg) {

        //获取user 对应的kgId
        int kgId = userService.findKgIdByUserId();
        if(kgId==0){
            return baseMapper.findBySearchVo(kg);
        }else {
            return baseMapper.findByKgId(kgId);
        }
    }

    public KindergartenEntity checkKgCodeUnique(String code) {
        return baseMapper.selectOne(Wrappers.<KindergartenEntity>query().eq("kg_code",code));
    }


    public KindergartenEntity findByName(String name){
        return baseMapper.selectOne(new QueryWrapper<KindergartenEntity>()
                .like("kg_name",name));
    }
}
